package com.toidep.fragment.mains;

import java.util.ArrayList;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.toidep.R;
import com.toidep.activities.MainActivity;
import com.toidep.base.BaseFragment;
import com.toidep.config.Constants;
import com.toidep.fragment.others.SearchFragment;
import com.toidep.fragment.others.VideoPlayerFragment;
import com.toidep.interfaces.ConfirmListener;
import com.toidep.interfaces.DialogListener;
import com.toidep.utilities.DialogUtility;
//import com.toidep.video.player.ChannelPlayer;

public class MainFragment extends BaseFragment implements OnClickListener{

	/**=========== Fragment Manager - start ===============
	 * Luu y Hai khi them fragment moi
	 * 1. Them bien fragment moi trong khung nay
	 * 2. Vao function  openFragmentScreen(int redirect, DialogListener dialogListener) them case cho fragment moi
	 **/
	private FragmentManager mFragmentManager;
	public BaseFragment mCurrentFragment;

	private ArrayList<BaseFragment> mFragmentOtherList;
	private ArrayList<BaseFragment> mFragmentMainList;
	
	private HomeFragment homeFragment;
	private FreeFragment freeFragment;
	private UpdateFragment updateFragment;
	private ModelFragment modelFragment;
	private AlbumFragment albumFragment;
	private VideoFragment videoFragment;
	private IntroductionFragment introductionFragment;
	private NewsFragment newsFragment;
//	private StoryFragment storyFragment;
//	private EventFragment eventFragment;
	private UserInfoFragment userInfoFragment;
	
	/**=========== Fragment Manager - end ===============**/	
	
	private ImageButton buttonSlide, buttonBack, buttonSearch;
	private TextView textViewLabelSideBar;
	private LinearLayout layoutHeader;
	private RelativeLayout layoutTitle, layoutSearch;

	private boolean isCreated = false; 

	View view;
	
	private MainActivity mainActivity;

	public MainFragment() {
		isCreated = true;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		view = inflater.inflate(R.layout.fragment_main, container, false);
		
		mainActivity = (MainActivity) getActivity();
		
		textViewLabelSideBar = (TextView) view.findViewById(R.id.textViewLabelSideBar);
		
		initFragmentManagement();
		
		initComponents();
		
		openFragmentScreen(Constants.CATEGORY_HOME, null);

		return view;
	}

	private void initComponents() {
		buttonSlide = (ImageButton) view.findViewById(R.id.buttonSlide);
		buttonBack = (ImageButton) view.findViewById(R.id.buttonBack);
		buttonSearch = (ImageButton) view.findViewById(R.id.buttonSearch);
		layoutTitle = (RelativeLayout) view.findViewById(R.id.layoutTitle);
		layoutSearch = (RelativeLayout) view.findViewById(R.id.layoutSearch);
		
		buttonSlide.setOnClickListener(this);
		buttonBack.setOnClickListener(this);
		buttonSearch.setOnClickListener(this);
		
		layoutHeader = (LinearLayout) view.findViewById(R.id.layoutHeaderMain);
		
	}
	
	/**
	 * Mo 1 fragment moi ra khi tu man hinh khac chuyen vao man hinh main
	 * @param redirect: bien dieu huong de mo Fragment tuong ung
	 */
	public void openFragmentScreen(int redirect, DialogListener dialogListener) {
		
		switch (redirect) {
		case Constants.CATEGORY_HOME:
			if (homeFragment == null)
				homeFragment = HomeFragment.newInstance();
			openFragmentScreen(homeFragment, dialogListener);
			break;
		case Constants.CATEGORY_FREE:
			if (freeFragment == null)
				freeFragment = FreeFragment.newInstance();
			openFragmentScreen(freeFragment, dialogListener);
			break;
		case Constants.CATEGORY_UPDATE:
			if (updateFragment == null)
				updateFragment = UpdateFragment.newInstance();
			openFragmentScreen(updateFragment, dialogListener);
			break;
		case Constants.CATEGORY_MODEL:
			if (modelFragment == null)
				modelFragment = ModelFragment.newInstance();
			openFragmentScreen(modelFragment, dialogListener);
			break;
		case Constants.CATEGORY_ALBUM:
			if (albumFragment == null)
				albumFragment = AlbumFragment.newInstance();
			openFragmentScreen(albumFragment, dialogListener);
			break;
		case Constants.CATEGORY_VIDEO:
			if (videoFragment == null)
				videoFragment = VideoFragment.newInstance();
			openFragmentScreen(videoFragment, dialogListener);
			break;
		case Constants.CATEGORY_HOME_INTRO:
			if (introductionFragment == null)
				introductionFragment = IntroductionFragment.newInstance();
			openFragmentScreen(introductionFragment, dialogListener);
			break;
		case Constants.CATEGORY_NEWS:
			if (newsFragment == null)
				newsFragment = NewsFragment.newInstance();
			openFragmentScreen(newsFragment, dialogListener);
			break;
//		case Constants.CATEGORY_STORY:
//			if (storyFragment == null)
//				storyFragment = StoryFragment.newInstance();
//			openFragmentScreen(storyFragment, dialogListener);
//			break;
//		case Constants.CATEGORY_EVENT:
//			if (eventFragment == null)
//				eventFragment = EventFragment.newInstance();
//			openFragmentScreen(eventFragment, dialogListener);
//			break;
		case Constants.CATEGORY_USER_INFO:
//			if (userInfoFragment == null)
			//Bug #229 -start
			UserInfoFragment userInfoFragment = UserInfoFragment.newInstance();
			openFragmentScreen(userInfoFragment, dialogListener);
			//Bug #229 -end
			break;
		case Constants.CATEGORY_SEARCH:
			SearchFragment searchFragment = SearchFragment.newInstance("", 0, false);
			initTabSearch(searchFragment);
			openFragmentScreen(searchFragment, dialogListener);
			break;
		}
	}

	/*********** Fragment Manager ***********/
	private void initFragmentManagement() {
		mFragmentManager = mainActivity.getSupportFragmentManager();
		mCurrentFragment = null;
		
		mFragmentMainList = new ArrayList<BaseFragment>();
		mFragmentOtherList = new ArrayList<BaseFragment>();

		/*
		 * Doan xu ly Activity bi os kill khien cac fragment chong len nhau
		 */
		/*try {
			while (mFragmentManager.getFragments().isEmpty() == false) {
				mFragmentManager.getFragments().clear();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}*/
		if (isCreated == true) {
			try {
				for (int i = mFragmentManager.getBackStackEntryCount() - 1; i >= 0; i--) {
					Log.e("MainActivity", "Remove fragment");
					mFragmentManager.popBackStack();
				}
			} catch (Exception e) { }
			
			isCreated = false;
		}
	}

	public void openFragmentScreen(BaseFragment newFragment, DialogListener dialogListener) {
		if (newFragment == null)
			return;
		
		if (newFragment == mCurrentFragment) {
			if (mainActivity.slidingMenu.isMenuShowing())
				mainActivity.toggle(null);
			return;
		}

		FragmentTransaction ft = mFragmentManager.beginTransaction();

		mainActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		/*
		 * An Fragment hien tai di
		 */
		if (mCurrentFragment != null) {
			ft.hide(mCurrentFragment);
		}
		
		mCurrentFragment = newFragment;
		if (newFragment.isRootFragment()) {
			/**
			 * La RootFragment
			 * Neu newFrament da ton tai thi remove 
			 * Sau do add vao cuoi list
			 * Neu chua ton tai thi add vao list
			 */
			if (isFragmentMainCreated(newFragment)) {
				mFragmentMainList.remove(newFragment);
				showFragment(mCurrentFragment);
			} else {
				ft.add(R.id.layoutContent, newFragment);
				ft.addToBackStack(null);
			}
			mFragmentMainList.add(newFragment);
		} else {
			/**
			 * Khong phai la RootFrament
			 * Them vao list
			 */
			ft.add(R.id.layoutContent, newFragment);
			ft.addToBackStack(null);
			mFragmentOtherList.add(newFragment);
		}

		ft.commit();

		if (dialogListener != null) {
			dialogListener.after();
		}
	}

	/**
	 * Loai bo cac fragment den fragment Root
	 */
	private void removeRootLoopFragment() {
		if (mCurrentFragment != null) {

			while (!mCurrentFragment.isRootFragment()) {
				closeTopFragmentScreen();
			}
		}
	}
	
	/**
	 * Move Fragement to Top
	 */
	private void moveTopFragment(ArrayList<BaseFragment> listFragment, BaseFragment baseFragment) {
		if (listFragment != null && baseFragment != null) {
			if (listFragment.size() > 0)
				listFragment.remove(baseFragment);
			listFragment.add(baseFragment);
			mCurrentFragment = baseFragment;
		}
	}

	private boolean isFragmentMainCreated(BaseFragment baseFragment) {
		if (mFragmentMainList.isEmpty() == false)
			return (mFragmentMainList.indexOf(baseFragment) != -1);
		return false;
	}
	
	/**
	 * Close fragment hien tai, Back lai fragment truoc do
	 */
	private void closeTopFragmentScreen() {
		if (mCurrentFragment.isRootFragment()) {
			if (mFragmentMainList != null && mFragmentMainList.size() > 1) {
				FragmentTransaction ft = mFragmentManager.beginTransaction();
				try {
					// Close Fragment hien tai
					mCurrentFragment.clear();
					mFragmentMainList.remove(mCurrentFragment);
					ft.remove(mCurrentFragment);
					
					// Open Fragment truoc do
					mCurrentFragment = mFragmentMainList.get(mFragmentMainList.size()-1);
				} catch (Exception e) { }
				ft.commit();
			} else {
				return;
			}
		} else if (mFragmentOtherList != null && mFragmentOtherList.size() > 0) {
			FragmentTransaction ft = mFragmentManager.beginTransaction();
			try {
				// Close Fragment hien tai
				mCurrentFragment.clear();
				mFragmentOtherList.remove(mFragmentOtherList.size()-1);
				ft.remove(mCurrentFragment);
				
				// Open Fragment truoc do
				if (mFragmentOtherList.size() > 0) { 
					mCurrentFragment = mFragmentOtherList.get(mFragmentOtherList.size()-1);
				} else {
					mCurrentFragment = mFragmentMainList.get(mFragmentMainList.size()-1);
				}
				 
			} catch (Exception e) { }
			ft.commit();
		} else {
			return;
		}
	}
	
	private void showFragment(BaseFragment baseFragment) {
		mainActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		FragmentTransaction ft = mFragmentManager.beginTransaction();
		ft.setCustomAnimations(R.anim.slide_in_right, 0);
		ft.show(baseFragment);
		baseFragment.setBaseValues();
		baseFragment.refresh();
		mCurrentFragment = baseFragment;
		ft.commit();
	}

	/**
	 * Close tat ca cac fragments co trong app
	 * Duoc goi khi nguoi dung close app
	 */
	private void finish() {
		mainActivity.clearFiles();
//		mainActivity.clearMemmoryCache();
		mainActivity.closeCache();
		
		mCurrentFragment = null;
		
		mFragmentMainList.clear();
		mFragmentOtherList.clear();
		
		mainActivity.finish();
	}

	public void onBackPressed(boolean isBackView) {
		if (mCurrentFragment.isSupperRootFragment()) {
			DialogUtility.showDialogConfirm(mainActivity, "", getString(R.string.text_confirm_exit), new ConfirmListener() {

				@Override
				public void doCancel() { }

				@Override
				public void doAccept() {
					finish();
				}
			});
		} else {
			if (isBackView) {
				removeRootLoopFragment();
			} else {
				closeTopFragmentScreen();
			}
			
			showFragment(mCurrentFragment);
		}
	}
	/*********** End Fragment Manager ***********/
	
	
	public void setTittle(String label) {
		try {
			if (textViewLabelSideBar != null) {
				textViewLabelSideBar.setText("" + label.toUpperCase());
			}
		} catch (Exception e) {
		}
	}
	
	public void showButtonSlide(boolean isShow) {
		if (buttonSlide == null || buttonBack == null || mainActivity == null)
			return;
		
		buttonSlide.setVisibility(View.VISIBLE);
		buttonBack.setVisibility(View.GONE);
		mainActivity.lockSlidingMenu(true);
		
		if (!isShow) {
			buttonSlide.setVisibility(View.GONE);
			buttonBack.setVisibility(View.VISIBLE);
			mainActivity.lockSlidingMenu(false);
		}
		
		showSearchLayout(false);
	}
	
	public void showSearchLayout(boolean isShow) {
		if (isShow) {
			layoutTitle.setVisibility(View.GONE);
			layoutSearch.setVisibility(View.VISIBLE);
		} else {
			layoutTitle.setVisibility(View.VISIBLE);
			layoutSearch.setVisibility(View.GONE);
		}
	}
	
	public RelativeLayout getSearchLayout() {
		return layoutSearch;
	}

	@Override
	public void onClick(View v) {
		
		if (v == buttonSlide) {
			mainActivity.openLeftMenu();
		} else if (v == buttonBack) {
			onBackPressed(mCurrentFragment.isBackView());
		} else  if (v == buttonSearch) {
			mainActivity.doClick(v.getId());
		}
	}

	public SearchFragment getSearchFragment() {
		return null;
	}
	
	public VideoPlayerFragment getVideoPlayerFragment() {
		if (mFragmentOtherList != null) {
			for (int i = 0; i < mFragmentOtherList.size(); i++) {
				BaseFragment baseFragment = mFragmentOtherList.get(i);
				if (baseFragment instanceof VideoPlayerFragment) {
					moveTopFragment(mFragmentOtherList, baseFragment);
					return (VideoPlayerFragment) baseFragment;
				}
			}
		}
		return null;
	}
	
	private void initTabSearch(SearchFragment searchFragment) {
		if (searchFragment == null)
			return;
		
		if (mCurrentFragment instanceof ModelFragment)
			searchFragment.setTabMode(0);
		else if (mCurrentFragment instanceof VideoFragment)
				searchFragment.setTabMode(1);
		else if (mCurrentFragment instanceof AlbumFragment)
			searchFragment.setTabMode(2);
		else if (mCurrentFragment instanceof NewsFragment)
			searchFragment.setTabMode(3);
		else if (mCurrentFragment instanceof StoryFragment)
			searchFragment.setTabMode(4);
		else if (mCurrentFragment instanceof EventFragment)
			searchFragment.setTabMode(5);
		else
			searchFragment.setTabMode(0);
	}
	
	public void showHeader(boolean isShow) {
		if (isShow == true) {
			layoutHeader.setVisibility(View.VISIBLE);
		} else {
			layoutHeader.setVisibility(View.GONE);
		}
	}
	
	public void onTouch(MotionEvent event) {
		Log.e("MainFragment", "onTouch");
		if (mCurrentFragment.getClass().getSimpleName().equals(VideoPlayerFragment.class.getSimpleName())) {
			((VideoPlayerFragment) mCurrentFragment).onTouchThis(event);
		}
	}

}
